﻿using System;
using System.Web;
using System.Web.SessionState;
using System.Collections.Specialized;
using System.Collections.Generic;

using DreamCube.Websites.BLL;
using DreamCube.Foundation.Serialization;
using DreamCube.Foundation.Basic.Utility;
using DreamCube.Framework.DataAccess.Basic;

namespace DreamCube.Websites.UI.Common.Agents
{
    /// <summary>
    /// EasyUIFormSave 的摘要说明
    /// </summary>
    public class EasyUIFormSave : IHttpHandler,IRequiresSessionState
    {
        //一个表单支持保存数据到多张表中
        //保存表名的字段的name前缀，格式如：_table_Name_1   value为：user
        private static String tableFieldPrefix = "_table_Name_";
        //保存前缀的字段的name前缀，格式如：_table_Prefix_1   value为：user_
        private static String prefixFieldPrefix = "_table_Prefix_";
        //保存主键的字段的name后缀，格式如：user_id_primaryKeyName  value为：主键的值
        private static String keyNameFieldEnds = "_primaryKeyName";

        public void ProcessRequest(HttpContext context)
        {
            OperationResult result = new OperationResult();
            try
            {
                //执行保存的方法
                DoSave(context);
                result.Status = true;
                context.Response.Write(MyJson.Serialize(result));
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
                result.Status = false;
                result.Msg = ex.ToString();
                context.Response.Write(MyJson.Serialize(result));
            }
            finally
            {
                context.Response.End();
            }
        }

        private Dictionary<String, Object> DoSave(HttpContext context)
        {
            NameValueCollection nameValues = context.Request.Form;
            if (nameValues != null)
            {
                //收集所有的字段项
                Dictionary<String, String> items = new Dictionary<String, String>();
                //收集到表名等信息之后，后续再循环一次进行处理
                Dictionary<String, String> tables = new Dictionary<String, String>();
                Dictionary<String, String> prefixs = new Dictionary<String, String>();
                //遍历处理每一个名值对
                for (Int32 i = 0; i < nameValues.Count; i++)
                {
                    //名称
                    String name = HttpUtility.UrlDecode(nameValues.GetKey(i));
                    //值（需要格式化）
                    String value = HttpUtility.UrlDecode(nameValues[i]);
                    if (name.StartsWith(tableFieldPrefix)) //表名字段
                        tables.Add(name, value);
                    else if (name.StartsWith(prefixFieldPrefix))//前缀字段
                        prefixs.Add(name, value);
                    else
                        items.Add(name, value);
                }
                Dictionary<String, DBObject> dbObjects = new Dictionary<String, DBObject>();
                //收集表名Key--前缀Value的数据
                Dictionary<String, String> tablePrefixs = new Dictionary<String, String>();
                //循环处理每一个表的数据
                foreach (KeyValuePair<String, String> table in tables)
                {
                    String tableName = table.Value;
                    //默认的前缀就是表名加下划线
                    String prefix = tableName + "_";
                    String tableIndex = MyString.RightOfLast(table.Key, "_");
                    //如果指定了表前缀，则采用指定的表前缀
                    if (prefixs.ContainsKey(prefixFieldPrefix + tableIndex))
                        prefix = prefixs[prefixFieldPrefix + tableIndex];
                    //把表名的前缀记录起来
                    if (!tablePrefixs.ContainsKey(tableName))
                        tablePrefixs.Add(tableName, prefix);
                    //添加一个表，以及其字段
                    if (!dbObjects.ContainsKey(tableName))
                    {
                        DBObject dbObject = new DBObject(WebSession.CurrentSystem.GetDB(), tableName);
                        foreach (KeyValuePair<String, String> item in items)
                        {
                            //如果前缀符合，则添加到指定的表中
                            if (item.Key.StartsWith(prefix))
                            {
                                //字段名
                                String fieldName = MyString.Right(item.Key, prefix);
                                if (fieldName.EndsWith(keyNameFieldEnds))
                                {
                                    fieldName = MyString.LeftOfLast(fieldName, keyNameFieldEnds);
                                    //如果指定的主键的值为空，可以直接继续循环了
                                    if (String.IsNullOrEmpty(item.Value)) continue;
                                }
                                dbObject.SetItemValue(fieldName, item.Value);
                            }
                        }
                        dbObjects.Add(tableName, dbObject);
                    }
                }
                List<DBObject> dbObjectXList = new List<DBObject>();
                foreach (KeyValuePair<String, DBObject> dbObj in dbObjects)
                    dbObjectXList.Add(dbObj.Value);
                DBObjectHelper.SaveDBObjectList(dbObjectXList, true, WebSession.CurrentSystem.GetDB());
                Dictionary<String, Object> returnVals = new Dictionary<String, Object>();
                returnVals.Add("__SaveResult__", true);
                //返回自增列的值到客户端（因为自增列是保存之后才生成的）
                for (Int32 i = 0, j = dbObjectXList.Count; i < j; i++)
                {
                    DBObject tempDBObject = dbObjectXList[i];
                    //自增列的值
                    Object identityValue = tempDBObject.GetItemValue(tempDBObject.Identity);
                    String tempIdentityPrefix = tablePrefixs[tempDBObject.TableName] + tempDBObject.Identity;
                    returnVals.Add(tempIdentityPrefix, identityValue);
                }
                //返回客户端的值
                return returnVals;
            }
            return null;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}